package com.flex.showdoc4j.generator;

import cn.hutool.core.date.DateUtil;
import com.flex.showdoc4j.executor.Wrapper;
import com.flex.showdoc4j.model.GeneratorSdkConfig;
import com.flex.showdoc4j.model.ParamModel;
import com.flex.showdoc4j.model.ReturnChildVariableModel;
import com.flex.showdoc4j.model.ReturnVariableModel;
import com.flex.showdoc4j.template.Template;
import com.flex.showdoc4j.template.TemplateFactory;

import java.util.*;

/**
 * 生成js模版
 * @author ganlt
 * @since 2019/10/25 10:09
 */
public class JsGeneratorSdk extends AbstractGeneratorSdk {
    public JsGeneratorSdk() {
    }

    @Override
    public SdkFile generatorSdk(GeneratorSdkConfig generatorSdkConfig, TemplateFactory templateFactory, Wrapper wrapper) {
        Template template = templateFactory.getTemplate();
        List<ParamModel> paramModels = wrapper.paramModelList();
        List<ReturnVariableModel> returnParamMap = wrapper.getReturnParamMap();
        String fileName = getNameByUrl(wrapper.getUrl(),generatorSdkConfig.getSuffixName());
        Map<String, Object> bind = new HashMap<>(6);
        bind.put("requestParams", paramModels);
        bind.put("url", wrapper.getUrl());
        bind.put("responseParams", returnParamMap);
        bind.put("name", fileName);
        bind.put("desc", wrapper.getDocModel().getDesc());
        bind.put("title", wrapper.getDocModel().getTitle());
        bind.put("isPager", wrapper.getDocModel().isPage());
        bind.put("date", DateUtil.format(new Date(),"YYYY-MM-dd HH:mm"));
        bind.put("author", wrapper.getConfiguration().getConfigModel().getAuthor());
        bind.put("version", wrapper.getConfiguration().getConfigModel().getVersion());

        List<ReturnChildVariableModel> childVariableModelList = new ArrayList<>();
        childs(wrapper.getReturnParamMap(), childVariableModelList);
        bind.put("childParams", childVariableModelList);

        String body = template.fileTemplateRender(generatorSdkConfig.getTemplatePath(), bind);

        return SdkFile.createSdkFile(fileName, generatorSdkConfig.getType(), body);
    }

    private void formatParams(List<ParamModel> paramModels) {
        for (ParamModel paramModel: paramModels) {
            paramModel.setName(firstUpperCase(paramModel.getName()));
        }

    }

    private void formatReturnParams(List<ReturnVariableModel> returnVariableModels){
        for (ReturnVariableModel returnVariableModel : returnVariableModels) {
            returnVariableModel.setName(firstUpperCase(returnVariableModel.getName()));
        }
    }

}
